package com.victor9ac.mashup.elasticsearch.logic;

import org.aspectj.lang.ProceedingJoinPoint;

import com.victor9ac.mashup.api.MashupDataType;
import com.victor9ac.mashup.elasticsearch.tasks.ElasticSearchOperation;

public class ElasticSearchBehaviour{

	

	ElasticSearchOperation elasticSearchOperation;
	


	public Object execute(String keyword,MashupDataType mashupDataType, ProceedingJoinPoint pjp) throws Throwable {

		
		Object objResponse = elasticSearchOperation
				.getFromMyPersistence(keyword, mashupDataType);

		Object aspectResult = manageSourceResult(pjp, objResponse,mashupDataType);

		
		return aspectResult;

	}
	
	public Object manageSourceResult(ProceedingJoinPoint pjp,
			Object objResponse, MashupDataType mashupDataType) throws Throwable {

		Object aspectResult = null;
		
		if (objResponse != null) {
			System.out.println("data found at ES");
			
			// devuelvo los datos obtenidos de ES	
			aspectResult = objResponse;

		} else {
			
			// no hay datos en persistencia(ES), los obtengo y los guardo.
			aspectResult = pjp.proceed();
			
			elasticSearchOperation.setFromMyPersistence(aspectResult,
					mashupDataType,getElasticIndexName(mashupDataType));//guardo en ES 
		}
		return aspectResult;
	}

	
	private String getElasticIndexName(MashupDataType mashupDataType) {
		String indexName = mashupDataType.toString().toLowerCase()+"-index";
		return indexName;
	}


	public void setElasticSearchOperation(
			ElasticSearchOperation elasticSearchOperation) {
		this.elasticSearchOperation = elasticSearchOperation;
	}

}
